<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>JavaScript及C# URI编码详解 - Foryun - Share</title>
  <meta name="renderer" content="webkit" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">


<meta name="author" content="Danic" /><meta name="description" content="混乱的URI编码 JavaScript中编码有三种方法:escape、encodeURI、encodeURIComponent C#中编码主要方" /><meta name="keywords" content="Blog, IT, Share, Record" />






<meta name="generator" content="Hugo 0.81.0 with theme even" />


<link rel="canonical" href="http://foryun.com.cn/post/share/uri%E7%BC%96%E7%A0%81%E8%AF%A6%E8%A7%A3/" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">

<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<link href="/sass/main.min.af7fd1da18d66c2b017df5b4cae508ef44cfcac3fb4c7c7a327fe4f4f9e28b08.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.css" integrity="sha256-7TyXnr2YU040zfSP+rEcz29ggW4j56/ujTPwjMzyqFY=" crossorigin="anonymous">


<meta property="og:title" content="JavaScript及C# URI编码详解" />
<meta property="og:description" content="混乱的URI编码 JavaScript中编码有三种方法:escape、encodeURI、encodeURIComponent C#中编码主要方" />
<meta property="og:type" content="article" />
<meta property="og:url" content="http://foryun.com.cn/post/share/uri%E7%BC%96%E7%A0%81%E8%AF%A6%E8%A7%A3/" /><meta property="article:section" content="post" />
<meta property="article:published_time" content="2021-03-15T15:12:17&#43;04:00" />
<meta property="article:modified_time" content="2021-03-15T15:12:17&#43;04:00" />

<meta itemprop="name" content="JavaScript及C# URI编码详解">
<meta itemprop="description" content="混乱的URI编码 JavaScript中编码有三种方法:escape、encodeURI、encodeURIComponent C#中编码主要方"><meta itemprop="datePublished" content="2021-03-15T15:12:17&#43;04:00" />
<meta itemprop="dateModified" content="2021-03-15T15:12:17&#43;04:00" />
<meta itemprop="wordCount" content="2029">
<meta itemprop="keywords" content="URI," /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="JavaScript及C# URI编码详解"/>
<meta name="twitter:description" content="混乱的URI编码 JavaScript中编码有三种方法:escape、encodeURI、encodeURIComponent C#中编码主要方"/>

<!--[if lte IE 9]>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
<![endif]-->

<!--[if lt IE 9]>
  <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<![endif]-->

</head>
<body>
  <div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/" class="logo">Foryun</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>
<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    <a href="/">
        <li class="mobile-menu-item">Home</li>
      </a><a href="/post/">
        <li class="mobile-menu-item">Archives</li>
      </a><a href="/tags/">
        <li class="mobile-menu-item">Tags</li>
      </a><a href="/categories/">
        <li class="mobile-menu-item">Categories</li>
      </a><a href="/diary/">
        <li class="mobile-menu-item">Diary</li>
      </a><a href="/record/">
        <li class="mobile-menu-item">Record</li>
      </a><a href="/game/">
        <li class="mobile-menu-item">Game</li>
      </a><a href="/about/">
        <li class="mobile-menu-item">About</li>
      </a>
  </ul>

  


</nav>

  <div class="container" id="mobile-panel">
    <header id="header" class="header">
        <div class="logo-wrapper">
  <a href="/" class="logo">Foryun</a>
</div>





<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
        <a class="menu-item-link" href="/">Home</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/post/">Archives</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/tags/">Tags</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/categories/">Categories</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/diary/">Diary</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/record/">Record</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/game/">Game</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/about/">About</a>
      </li>
  </ul>
</nav>

    </header>

    <main id="main" class="main">
      <div class="content-wrapper">
        <div id="content" class="content">
          <article class="post">
    
    <header class="post-header">
      <h1 class="post-title">JavaScript及C# URI编码详解</h1>

      <div class="post-meta">
        <span class="post-time"> 2021-03-15 </span>
        <div class="post-category">
            <a href="/categories/share/"> Share </a>
            </div>
          <span class="more-meta"> 约 2029 字 </span>
          <span class="more-meta"> 预计阅读 5 分钟 </span>
        <span id="busuanzi_container_page_pv" class="more-meta"> <span id="busuanzi_value_page_pv"><img src="/img/spinner.svg" alt="spinner.svg"/></span> 次阅读 </span>
      </div>
    </header>

    <div class="post-toc" id="post-toc">
  <h2 class="post-toc-title">文章目录</h2>
  <div class="post-toc-content always-active">
    <nav id="TableOfContents">
  <ul>
    <li><a href="#混乱的uri编码">混乱的URI编码</a></li>
    <li><a href="#escape不推荐使用">escape：不推荐使用</a></li>
    <li><a href="#encodeuri用于对网址编码不包含参数">encodeURI：用于对网址编码(不包含参数)</a></li>
    <li><a href="#encodeuricomponent用于对网址参数进行编码">encodeURIComponent:用于对网址参数进行编码</a></li>
    <li><a href="#serverurlencode--httputilityurlencode不推荐">Server.UrlEncode &amp;&amp; HttpUtility.UrlEncode:不推荐</a></li>
    <li><a href="#uriescapeuristring用于对网址编码不包含参数">Uri.EscapeUriString:用于对网址编码(不包含参数)</a></li>
    <li><a href="#uriescapedatastring用于对网址参数进行编码">Uri.EscapeDataString:用于对网址参数进行编码</a></li>
    <li><a href="#小结">小结</a></li>
  </ul>
</nav>
  </div>
</div>
    <div class="post-content">
      <h1 id="混乱的uri编码">混乱的URI编码</h1>
<p>　　JavaScript中编码有三种方法:escape、encodeURI、encodeURIComponent</p>
<p>　　C#中编码主要方法：HttpUtility.UrlEncode、Server.UrlEncode、Uri.EscapeUriString、Uri.EscapeDataString</p>
<p>　　JavaScript中的还好，只提供了三个，C#中主要用的就有这么多，还没有列出其他编码(HTML)，一多就弄不明白，弄不明白就心生恐惧，心生恐惧就变得苦逼，本文就向大家详细解释在JavaScript及C#中如何对URI进行编码的方法(注：本文不涉及到其他编码)。</p>
<h1 id="escape不推荐使用">escape：不推荐使用</h1>
<p>　　原因：eacape是BOM中的方法，只能对ASCII符号正确编码，而encodeURI、encodeURIComponent可以对所有的Unicode符号编码。ECMAScript v3 反对使用该方法，应用使用 decodeURI() 和 decodeURIComponent() 替代它。</p>
<p>　　escape不编码字符有69个：*<strong>，+，-，.，/，@，_，0-9，a-z，A-Z</strong></p>
<h1 id="encodeuri用于对网址编码不包含参数">encodeURI：用于对网址编码(不包含参数)</h1>
<p>　　encodeURI不编码字符有82个：<strong>!，#，$，&amp;，'，(，)，*，+，,，-，.，/，:，;，=，?，@，_，~，0-9，a-z，A-Z</strong></p>
<p>　　encodeURI就是为这个而设计的。encodeURI不对URI中的特殊字符进行编码，如冒号(:)、斜杠(/)。下面看个示例：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">encodeURI(&#34;http://www.cnblogs.com/a file with spaces.html&#34;)
// outputs http://www.cnblogs.com/a%20file%20with%20spaces.html
</code></pre></td></tr></table>
</div>
</div><p>　　可以看到仅仅把空格替换成了20%，所以此方法可用于对网址进行编码。</p>
<p>　　由于encodeURI不对冒号(:)、斜杠(/)进行编码，所以如果参数(如把网址作为参数)中包含冒号(:)、斜杠(/)，就会解析出错，所以此方法不能对参数进行编码。</p>
<h1 id="encodeuricomponent用于对网址参数进行编码">encodeURIComponent:用于对网址参数进行编码</h1>
<p>　　encodeURIComponent不编码字符有71个：<strong>!， &lsquo;，(，)，*，-，.，_，~，0-9，a-z，A-Z</strong></p>
<p>　　可以看到此方法对:/都进行了编码，所以不能用它来对网址进行编码。由于此方法对中文，空格，井号(#)，斜线(/)，冒号(:)都进行了编码，所以适合对URI中的参数进行编码。看下面的示例：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">var param=&#34;博客园&#34;;
var url=&#34;http://www.cnblogs.com/?key=&#34;+encodeURIComponent(param)+&#34;&amp;page=1&#34;;
console.log(url);//outputs http://www.cnblogs.com/?key=%E5%8D%9A%E5%AE%A2%E5%9B%AD&amp;page=1
</code></pre></td></tr></table>
</div>
</div><p>　　可以看到，这正是我们想要的结果(这里只对需要编码的参数(page=1不需要编码)进行了编码)。</p>
<h1 id="serverurlencode--httputilityurlencode不推荐">Server.UrlEncode &amp;&amp; HttpUtility.UrlEncode:不推荐</h1>
<p>　　把这两个放到一起说是因为这两个方法在绝大多数情况下是一样的。它们的区别是HttpUtility.UrlEncode默认使用UTF8格式编码，而Server.UrlEncode是使用系统预设格式编码，Server.UrlEncode使用系統预设编码做为参数调用HttpUtility.UrlEncode编码，所以如果系统全局都用UTF8格式编码，这两个方法就是一样的。</p>
<p>　　这两个方法是怎么编码的呢，我们来看个示例：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">string url1 = &#34;http://www.cnblogs.com/a file with spaces.html?a=1&amp;b=博客园#abc&#34;;
Response.Write(HttpUtility.UrlEncode(url1) );

//output
http%3a%2f%2fwww.cnblogs.com%2fa+file+with+spaces.html%3fa%3d1%26b%3d%e5%8d%9a%e5%ae%a2%e5%9b%ad%23abc
</code></pre></td></tr></table>
</div>
</div><p>　　由上面的例子我们可以看出，HttpUtility.UrlEncode对冒号(:)和斜杠(/)进行了编码，所以不能用来对网址进行编码。</p>
<p>　　那么能不能对参数进行编码呢，答案也是否定的。因为在参数中空格应该被编码为%20而不是被HttpUtility.UrlEncode编码为加号(+)，所以不推荐用这两个方法对URI进行编码。</p>
<h1 id="uriescapeuristring用于对网址编码不包含参数">Uri.EscapeUriString:用于对网址编码(不包含参数)</h1>
<p>　　我们还是用例子说话：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">string url1 = &#34;http://www.cnblogs.com/a file with spaces.html?a=1&amp;b=博客园#abc&#34;;
Response.Write( Uri.EscapeUriString(url1));
//outputs:
http://www.cnblogs.com/a%20file%20with%20spaces.html?a=1&amp;b=%E5%8D%9A%E5%AE%A2%E5%9B%AD#abc
</code></pre></td></tr></table>
</div>
</div><p>　　可以看出，Uri.EscapeUriString对空格进行了编码，也对中文进行了编码，但对冒号(:)、斜杠(/)和井号(#)未编码，所以此方法可以用于网址进行编码，但不能对参数进行编码，作用类似JavaScript中的encodeURI方法。</p>
<h1 id="uriescapedatastring用于对网址参数进行编码">Uri.EscapeDataString:用于对网址参数进行编码</h1>
<p>　　仍然用例子说话：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">string url1 = &#34;http://www.cnblogs.com/a file with spaces.html?a=1&amp;b=博客园#abc&#34;;
Response.Write(Uri.EscapeDataString(url1));
//outputs:
http%3A%2F%2Fwww.cnblogs.com%2Fa%20file%20with%20spaces.html%3Fa%3D1%26b%3D%E5%8D%9A%E5%AE%A2%E5%9B%AD%23abc
</code></pre></td></tr></table>
</div>
</div><p>　　可以看出，Uri.EscapeDataString对冒号(:)、斜杠(/)、空格、中文、井号(#)都进行了编码，所以此方法不可以用于网址进行编码，但可以用于对参数进行编码，作用类似JavaScript中的encodeURIComponent方法。</p>
<h1 id="小结">小结</h1>
<p>　　<strong>在JavaScript中推荐的做法是用encodeURI对URI的网址部分编码，用encodeURIComponent对URI中传递的参数进行编码。</strong></p>
<p>　　<strong>在C#中推荐的做法是用Uri.EscapeUriString对URI的网址部分编码，用Uri.EscapeDataString对URI中传递的参数进行编码。</strong></p>
<p>　　解码部分就不说了，与编码方法相对应。</p>

    </div>

    <div class="post-copyright">
  <p class="copyright-item">
    <span class="item-title">文章作者</span>
    <span class="item-content">Danic</span>
  </p>
  <p class="copyright-item">
    <span class="item-title">上次更新</span>
    <span class="item-content">
        2021-03-15
        
    </span>
  </p>
  
  
</div>
<footer class="post-footer">
      <div class="post-tags">
          <a href="/tags/uri/">URI</a>
          </div>
      <nav class="post-nav">
        <a class="prev" href="/post/share/pako.js%E7%AE%80%E5%8D%95%E4%BD%BF%E7%94%A8/">
            <i class="iconfont icon-left"></i>
            <span class="prev-text nav-default">pako.js简单使用</span>
            <span class="prev-text nav-mobile">上一篇</span>
          </a>
        <a class="next" href="/post/unitygameframework/gameframework/">
            <span class="next-text nav-default">GameFramework</span>
            <span class="next-text nav-mobile">下一篇</span>
            <i class="iconfont icon-right"></i>
          </a>
      </nav>
    </footer>
  </article>
        </div>
        

  <span id="/post/share/uri%E7%BC%96%E7%A0%81%E8%AF%A6%E8%A7%A3/" class="leancloud_visitors" data-flag-title="JavaScript及C# URI编码详解">
		<span class="post-meta-item-text">文章阅读量 </span>
		<span class="leancloud-visitors-count">0</span>
		<p></p>
	  </span>
  <div id="vcomments"></div>
  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src='//unpkg.com/valine/dist/Valine.min.js'></script>
  <script type="text/javascript">
    new Valine({
        el: '#vcomments' ,
        appId: 'insXINA0D2ccQdcEfEcMSjgn-gzGzoHsz',
        appKey: 'HEAEkloDNn3aFg4Yr1W4iGM3',
        notify:  false ,
        verify:  false ,
        avatar:'mm',
        placeholder: '说点什么吧...',
        visitor:  true 
    });
  </script>

  

      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="social-links">
      <a href="mailto:1186976350@qq.com" class="iconfont icon-email" title="email"></a>
      <a href="https://github.com/DanicCheng" class="iconfont icon-github" title="github"></a>
      <a href="https://space.bilibili.com/2920221?spm_id_from=333.788.b_765f7570696e666f.2" class="iconfont icon-bilibili" title="bilibili"></a>
  
</div>

<div class="copyright">
  <span class="power-by">
    由 <a class="hexo-link" href="https://gohugo.io">Hugo</a> 强力驱动
  </span>
  <span class="division">|</span>
  <span class="theme-info">
    主题 - 
    <a class="theme-link" href="https://github.com/olOwOlo/hugo-theme-even">Even</a>
  </span>

  <div class="busuanzi-footer">
    <span id="busuanzi_container_site_pv"> 本站总访问量 <span id="busuanzi_value_site_pv"><img src="/img/spinner.svg" alt="spinner.svg"/></span> 次 </span>
      <span class="division">|</span>
    <span id="busuanzi_container_site_uv"> 本站总访客数 <span id="busuanzi_value_site_uv"><img src="/img/spinner.svg" alt="spinner.svg"/></span> 人 </span>
  </div>

  <span class="copyright-year">
    &copy; 
    2017 - 
    2021<span class="heart"><i class="iconfont icon-heart"></i></span><span>Foryun</span>
  </span>

  <span class="beian">
    
    备案号：<a href="https://beian.miit.gov.cn" target="_blank">粤ICP备18045119号</a>
    
  </span>

</div>

    </footer>

    <div class="back-to-top" id="back-to-top">
      <i class="iconfont icon-up"></i>
    </div>
  </div>
  
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/slideout@1.0.1/dist/slideout.min.js" integrity="sha256-t+zJ/g8/KXIJMjSVQdnibt4dlaDxc9zXr/9oNPeWqdg=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.js" integrity="sha256-XVLffZaxoWfGUEbdzuLi7pwaUJv1cecsQJQqGLe7axY=" crossorigin="anonymous"></script>



<script type="text/javascript" src="/js/main.min.c99b103c33d1539acf3025e1913697534542c4a5aa5af0ccc20475ed2863603b.js"></script>

<script id="baidu_analytics">
  var _hmt = _hmt || [];
  (function() {
    if (window.location.hostname === 'localhost') return;
    var hm = document.createElement("script"); hm.async = true;
    hm.src = "https://hm.baidu.com/hm.js?57ed19d6fdd95893edd119b86ac49dab";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
  })();
</script>

<script id="baidu_push">
  (function(){
    if (window.location.hostname === 'localhost') return;
    var bp = document.createElement('script'); bp.async = true;
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
      bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
    }
    else {
      bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
  })();
</script>




</body>
</html>
